const Router = require("koa-router");
const router = new Router();

router.post("/order/batchDelete", (ctx) => {
  try {
    console.log("=== 批量删除接口调试信息 ===");
    console.log("请求方法:", ctx.method);
    console.log("请求URL:", ctx.url);
    console.log("请求头:", ctx.headers);
    console.log("原始请求体:", ctx.request.body);
    console.log("请求体类型:", typeof ctx.request.body);
    
    let orderIds = [];
    
    // 处理各种可能的请求体格式
    if (typeof ctx.request.body === "string") {
      console.log("处理字符串请求体");
      orderIds = ctx.request.body.split(',').map(id => id.trim()).filter(id => id);
    } 
    else if (Buffer.isBuffer(ctx.request.body)) {
      console.log("处理Buffer请求体");
      const bodyStr = ctx.request.body.toString();
      orderIds = bodyStr.split(',').map(id => id.trim()).filter(id => id);
    }
    else if (typeof ctx.request.body === "object" && ctx.request.body !== null) {
      console.log("处理对象请求体");
      
      // 尝试从常见属性中提取订单号
      const possibleKeys = ['orderIds', 'orders', 'ids', 'data'];
      for (const key of possibleKeys) {
        if (ctx.request.body[key]) {
          console.log(`找到键: ${key}, 值:`, ctx.request.body[key]);
          
          if (typeof ctx.request.body[key] === "string") {
            orderIds = ctx.request.body[key].split(',').map(id => id.trim()).filter(id => id);
            break;
          } else if (Array.isArray(ctx.request.body[key])) {
            orderIds = ctx.request.body[key].filter(id => id && id.toString().trim() !== "");
            break;
          }
        }
      }
      
      // 如果还没找到，尝试将整个对象转换为数组
      if (orderIds.length === 0) {
        console.log("尝试将整个对象转换为数组");
        try {
          const values = Object.values(ctx.request.body);
          orderIds = values.filter(value => 
            value && value.toString().trim() !== ""
          ).map(value => value.toString().trim());
        } catch (e) {
          console.error("转换对象值失败:", e);
        }
      }
    }
    
    console.log("提取的订单号:", orderIds);

    // 验证参数
    if (!Array.isArray(orderIds) || orderIds.length === 0) {
      console.log("参数验证失败");
      ctx.body = {
        code: 400,
        success: false,
        message: "参数错误：请提供有效的订单号",
        data: null,
      };
      return;
    }

    // 模拟删除操作
    console.log(`模拟删除订单: ${orderIds.join(", ")}`);

    // 返回成功响应
    ctx.body = {
      code: 200,
      success: true,
      message: "批量删除成功",
      data: {
        deletedOrders: orderIds,
        count: orderIds.length,
      },
    };
    
  } catch (error) {
    console.error("批量删除接口出错:", error);
    ctx.body = {
      code: 500,
      success: false,
      message: `服务器内部错误: ${error.message}`,
      data: null,
    };
  }
});

module.exports = router;